<template>
  <div>
    <layout title="配置视频" :footer="false" description="横版 16:9, 1920*1080，竖版  9:16 1080*1920">
      <a-upload
        list-type="picture-card"
        :file-list="fileList"
        :beforeUpload="beforeUpload"
        multiple
        @change="handleChange"
        @preview="handlePreview"
      >
        <div v-if="fileList.length <= limit">
          <a-icon type="plus" />
          <div class="ant-upload-text"> 上传 </div>
        </div>
      </a-upload>
    </layout>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <div id="myVideo"></div>
    </a-modal>
  </div>
</template>

<script>
import layout from '../layout'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

function getPic(url){
  // 获取视频封面图
  return new Promise(function (resolve) {
    let dataURL = "";
    const video = document.createElement("video");
    video.setAttribute("crossOrigin", "anonymous"); // 处理跨域
    video.setAttribute("src", url);
    video.setAttribute("preload", "auto");
    video.addEventListener("loadeddata", function () {
      const canvas = document.createElement("canvas");
      const width = video.videoWidth || 400; // canvas的尺寸和图片一样
      const height = video.videoHeight || 240; // 设置默认宽高为  400  240
      canvas.width = width;
      canvas.height = height;
      canvas.getContext("2d").drawImage(video, 0, 0, width, height); // 绘制canvas
      dataURL = canvas.toDataURL("image/jpeg"); // 转换为base64
      resolve(dataURL);
    });
  });
}

function dataURItoBlob(base64Data) {
    // 转Blob流
    // console.log(base64Data);//data:image/png;base64,
    var byteString;
    if(base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);//base64 解码
    else{
        byteString = unescape(base64Data.split(',')[1]);
    }
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

    // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    // var ia = new Uint8Array(arrayBuffer);//创建视图
    var ia = new Uint8Array(byteString.length);//创建视图
    for(var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ia], {
        type: mimeString
    });
    return blob;
}

export default {
  data() {
    return {
      limit: 99999,
      fileList:[],
      previewImage:'',
      previewVisible:false,
      list:[]
    }
  },
  methods:{
    async beforeUpload(file){
      // console.log(file)
      if(!(file.type === 'video/mp4')){
        this.$message.error('只能上传mp4文件')
        return Promise.reject()
      }
      this.fileList.push({
        uid: file.uid,
        name: file.name,
        status: 'uploading'
      })
      let run = () => {
        return new Promise((resolve) => {
          setTimeout(async () => {
            let filePreview = await getBase64(file);
            let pic = await getPic(filePreview)
            let Blob = dataURItoBlob(filePreview)
            let idx = this.fileList.findIndex(e=>e.uid == file.uid)
            this.fileList.splice(idx, 1, {
              uid: file.uid,
              name: file.name,
              url:pic,
              preview: filePreview,
              file: {name: file.name, blob:Blob}
            })
            this.list.push({name: file.name, blob:Blob})
            this.$emit('update:form', this.list)
            resolve()
          }, 300);
        });
      }
      await run()
      return Promise.reject()
    },
    async handlePreview(file) {
      // console.log(file.preview)
      // 解决video无法重新更新视频的bug
      this.previewVisible = true;
      this.$nextTick(()=>{
      //   <video id="myVideo" style="width: 100%" controls >
      // </video>
        let video = document.createElement("video")
        video.controls = true
        video.width = 478
        let sourceDom = document.createElement("source")
        sourceDom.src = file.preview
        let myVideo = document.getElementById('myVideo')
        video.appendChild(sourceDom)
        myVideo.appendChild(video)
        this.previewImage = file.preview;
      })
    },
    handleChange({ fileList }){
      this.fileList = fileList
      this.list = fileList.map(e=>e.file)
      this.$emit('update:form', this.list)
    },
  },
  watch:{
    previewVisible(val){
      if(!val){
        // 清除video中的内容
        let myVideo = document.getElementById('myVideo')
        let child = myVideo.lastElementChild
        while(child){
          myVideo.removeChild(child); 
          child = myVideo.lastElementChild; 
        }
      }
    }
  },
  components:{layout},
}
</script>

<style lang="less" scoped>

</style>